package cn.monkey.io.transport.netty.server.codec.protocol.tcp.http;

import cn.monkey.io.transport.netty.utils.ChannelHandlerUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.util.function.Consumer;

public interface HttpServerProtocolConsumer extends Consumer<Channel> {

    HttpServerProtocolConfig httpServerProtocolConfig();

    @Override
    default void accept(Channel channel) {
        ChannelPipeline pipeline = channel.pipeline();
        HttpServerProtocolConfig httpServerProtocolConfig = this.httpServerProtocolConfig();
        pipeline.addLast(ChannelHandlerUtils.normalizeName(HttpServerCodec.class), new HttpServerCodec(httpServerProtocolConfig.getMaxInitialLineLength(), httpServerProtocolConfig.getMaxHeaderSize(), httpServerProtocolConfig.getMaxChunkSize()))
                .addLast(ChannelHandlerUtils.normalizeName(ChunkedWriteHandler.class), new ChunkedWriteHandler())
                .addLast(ChannelHandlerUtils.normalizeName(HttpObjectAggregator.class), new HttpObjectAggregator(httpServerProtocolConfig.getMaxContentLength(), httpServerProtocolConfig.isCloseOnExpectationFailed()));
    }
}
